package offer;

/**
 * @author LongYongjiang
 */
@FunctionalInterface
public interface WinnerOfGame {
    boolean winnerOfGame(String colors);
}

class WinnerOfGameTest{
    static final String TEST_01 = "AAABABB";
    static final String TEST_02 = "AAAABBBB";
    public static void main(String[] args) {
        new WinnerOfGameImpl2().winnerOfGame(TEST_02);
    }
}

class WinnerOfGameImpl1 implements WinnerOfGame{
    /**
     * 时间o（n），空间o（n）
     * @return
     */
    @Override
    public boolean winnerOfGame(String colors) {
        int a = canDelete(colors, true);
        int b = canDelete(colors, false);
        return a - 1 >= b;

    }
    private int canDelete(String s, boolean isA){
        String digit;
        if(isA) {
            digit = "B";
        }else {
            digit = "A";
        }
        String[] tokens = s.split(digit);
        int canDeleteNum = 0;
        for(String token : tokens){
            if(token.length() >= 3){
                canDeleteNum += token.length() - 2;
            }
        }
        return canDeleteNum;
    }
}


class WinnerOfGameImpl2 implements WinnerOfGame{

    @Override
    public boolean winnerOfGame(String colors) {
        if(colors == null || colors.length() < 3){
            return false;
        }
        int a = 0, b = 0;
        int n = colors.length();
        char pre = colors.charAt(0);
        int sameNumber = 1;
        for (int i = 1; i < n; i++) {
            if(colors.charAt(i) == pre){
                sameNumber++;
            }else{
                if(pre == 'A'){
                    if(sameNumber >= 3){
                        a += sameNumber - 2;
                    }
                    pre = 'B';
                }else{
                    if(sameNumber >= 3){
                        b += sameNumber - 2;
                    }
                    pre = 'A';
                }
                sameNumber = 1;
            }
        }
        if(sameNumber >= 3){
            if(pre == 'A'){
                a += sameNumber - 2;
            }else{
                b += sameNumber - 2;
            }
        }
        return a > b;

    }
}